package fr.excilys.gwt.communication.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;

import fr.excilys.gwt.communication.shared.LoginException;
import fr.excilys.gwt.communication.shared.LoginService;
import fr.excilys.gwt.communication.shared.LoginServiceAsync;
import fr.excilys.gwt.communication.shared.User;

public class LoginPanel extends Composite {

	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);

	private TextBox usernameInput;

	private PasswordTextBox passwordInput;

	public LoginPanel() {
		FlexTable table = new FlexTable();
		// Ajout d'un titre
		Label title = new Label("Connexion");
		table.setWidget(0, 0, title);
		// Ajout du champ utilisateur
		Label userNameLabel = new Label("Utilisateur : ");
		table.setWidget(1, 0, userNameLabel);
		usernameInput = new TextBox();
		table.setWidget(1, 1, usernameInput);
		// Ajout du champ mot de passe
		Label passwordLabel = new Label("Mot de passe : ");
		table.setWidget(2, 0, passwordLabel);
		passwordInput = new PasswordTextBox();
		table.setWidget(2, 1, passwordInput);
		// Ajout du bouton de connexion
		Button loginButton = new Button("Connexion");
		loginButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				attemptLogin();
			}
		});
		table.setWidget(3, 0, loginButton);
		// Initialisation
		initWidget(table);
	}

	private void attemptLogin() {
		loginService.login(usernameInput.getText(), passwordInput.getText(),
				new AsyncCallback<User>() {
					@Override
					public void onSuccess(User user) {
						Window.alert("Bienvenu " + user.toString());
					}

					@Override
					public void onFailure(Throwable caught) {
						try {
							throw caught;
						} catch (LoginException le) {
							Window.alert("Erreur de connexion : "
									+ caught.getMessage());
						} catch (Throwable t) {
							Window.alert("Erreur inconnue : "
									+ caught.getMessage());
						}
					}
				});
	}
}
